﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;

namespace ReportGenerators.QuanLyKho.ThongKeTonTheoNhaCungCap
{
    public partial class FrmTongHopTienHangTheoNhaCungCap_1 : BasicForms.FrmSupportPrintableComponents
    {
        public FrmTongHopTienHangTheoNhaCungCap_1()
        {
            InitializeComponent();
        }

        private void FrmTongHopGiaTriTheoNhaCungCap_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedIndex = 19;

                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Merge(DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataView.ToTable());
                dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());  //Chỉ lấy những hàng TrangThai=1.

                gridControlDsDoiTac.DataSource = dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsDoiTac.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewTienTheoNCC.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }

            chkChooseAllDoiTac.Checked = true;
            FormatNumberInGridView(gridViewTienTheoNCC);
            FormatNumberInGridView(gridViewDsDoiTac);
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkChooseAllDoiTac_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                foreach (DataRow row in dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Rows)
                {
                    row["Choose"] = chkChooseAllDoiTac.Checked;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;

            Guid khoID = Guid.Empty;
            if (cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty)
                khoID = (Guid)cmbKho.EditValue;

            BasicForms.FrmProgressBar.StartShowProgress("Đang xử lý");
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand(); cmd.CommandTimeout = Config.TimeOut;

                dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.Clear();
                dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Clear();

                ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayBatDau);
                int count = 1;
                int total = dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Select("Choose = 1").Length;
                int totalSach = dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Rows.Count;

                //Tính tồn các hàng hóa chi tiết
                foreach (DataRow row in dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Rows)
                {
                    BasicForms.FrmProgressBar.Status = string.Format("Đang xử lý tính tồn hàng hóa {0}/{1}", count, totalSach);
                    count++;

                    Guid vatTuHangHoaID = (Guid)row["ID"];
                    VatTuHangHoa vatTuHangHoa = DanhMucVatTuHangHoa.Instance.GetByID(vatTuHangHoaID);
                    if (vatTuHangHoa == null)
                        break;
                    TonKho tonKho = new TonKho();
                    decimal donGiaVon = 0;

                    //Lấy giá vốn trung bình còn lại trong kho
                    if (khoID == Guid.Empty)
                    {
                        tonKho = TonKho.CalculateTongTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVao(cmd, ngayKetThuc, vatTuHangHoaID);
                        //donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonMuaTrungBinhToanBoCacKhoByID(vatTuHangHoa.ID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc);
                        donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonTrungBinhTheoGiaTriConLaiToanBoCacKhoByID(vatTuHangHoa.ID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc);
                    }
                    else
                    {
                        tonKho = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, ngayKetThuc, khoID, vatTuHangHoaID);
                        //donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonMuaTrungBinhToanBoTheoKhoByID(vatTuHangHoa.ID, khoID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc);
                        donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonTrungBinhTheoGiaTriConLaiToanBoTheoKhoByID(vatTuHangHoa.ID, khoID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc);
                    }

                    DataRow addedRow = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.NewRow();
                    addedRow["Ma"] = vatTuHangHoa.Ma;
                    addedRow["Ten"] = vatTuHangHoa.Ten;
                    if (vatTuHangHoa.DoiTuongNghiepVu != null)
                        addedRow["DoiTuongNghiepVuID"] = vatTuHangHoa.DoiTuongNghiepVu.ID;
                    else
                        addedRow["DoiTuongNghiepVuID"] = Guid.Empty;
                    addedRow["SoLuongTon"] = tonKho.SoLuong;
                    addedRow["GiaTriTongTon"] = tonKho.SoLuong * donGiaVon;
                    addedRow["GiaTriTongTonGiaBia"] = tonKho.SoLuong * vatTuHangHoa.GiaBia;

                    dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Rows.Add(addedRow);
                }

                //Tính tổng từng nhà cung cấp
                count = 0;
                try
                {
                    DataRow rowStatic = dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.NewDoiTuongNghiepVuRow();
                    rowStatic["ID"] = Guid.Empty;
                    rowStatic["Ma"] = "";
                    rowStatic["Ten"] = "";
                    rowStatic["LaPhongBan"] = true;
                    rowStatic["LaNhanVien"] = true;
                    rowStatic["LaKhachHang"] = true;
                    rowStatic["LaNhaCungCap"] = true;
                    rowStatic["LaNganHang"] = true;
                    rowStatic["MaSoThue"] = "";
                    dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Rows.Add(rowStatic);
                }
                catch (Exception ex)
                {
                }
               

                foreach (DataRow row in dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Rows)
                {
                    BasicForms.FrmProgressBar.Status = string.Format("Đã tính toán được {0} / {1} nhà cung cấp", count, total);

                    if (row["Choose"] is bool && (bool)row["Choose"])
                    {
                        Guid dtnvID = (Guid)row["ID"];
                        DoiTuongNghiepVu doiTuongNghiepVu = DanhMucDoiTuongNghiepVu.Instance.GetByID(dtnvID);

                        object soLuong, giaBia, giaVon;
                        soLuong = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(SoLuongTon)", string.Format("DoiTuongNghiepVuID = '{0}'", dtnvID));
                        giaVon = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(GiaTriTongTon)", string.Format("DoiTuongNghiepVuID = '{0}'", dtnvID));
                        giaBia = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(GiaTriTongTonGiaBia)", string.Format("DoiTuongNghiepVuID = '{0}'", dtnvID));

                        DataRow addedRow = dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.NewRow();

                        addedRow["MaNCC"] = doiTuongNghiepVu.Ma;
                        addedRow["TenNCC"] = doiTuongNghiepVu.Ten;
                        if (soLuong is decimal)
                            addedRow["SoLuong"] = (decimal)soLuong;
                        if (giaBia is decimal)
                            addedRow["GiaBia"] = (decimal)giaBia;
                        if (giaVon is decimal)
                            addedRow["GiaVon"] = (decimal)giaVon;

                        dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.Rows.Add(addedRow);
                        count++;
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
                BasicForms.FrmProgressBar.FinishShowProgress();
            }

            gridControlTienTheoNCC.DataSource = dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap;
            //AlphabeticSort(dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap, "TenNCC", 0).DefaultView; 
            FormatNumberInGridView(gridViewTienTheoNCC);
            FormatNumberInGridView(gridViewDsDoiTac);
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeader(true, gridControlTienTheoNCC, true, true, "Thống kê tổng hợp tiền theo nhà cung cấp", "");
        }

        private DataTable AlphabeticSort(DataTable dtTable, string sortColumn, int sortOrder)
        {
            DataSet dsSorted = new DataSet();
            string columnKey = sortColumn;
            string sortDirection = "";
            string sortFormat = "{0} {1}";
            switch (sortOrder)
            {
                case 0:
                    sortDirection = "ASC";
                    break;
                case 1:
                    sortDirection = "DESC";
                    break;
                default:
                    sortDirection = "ASC";
                    break;
            }

            dtTable.DefaultView.Sort = string.Format(sortFormat, columnKey, sortDirection);

            return dtTable.DefaultView.Table;
        }

        private DataTable GetHangDaCoGiaoDich(SqlCommand cmd, Guid selectedKhoID, DateTime ngayKetThuc)
        {
            try
            {
                ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayKetThuc);
                if (selectedKhoID != null && selectedKhoID != Guid.Empty)
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID, KhoID \n" +
                                                    "FROM NhatKyKho \n" +
                                                    "WHERE  KhoID = @KhoID AND @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi \n" +
                                                    "   AND VatTuHangHoaID is not null  \n" +
                                                    "UNION \n" +
                                                    "SELECT DISTINCT VatTuHangHoaID, KhoID \n" +
                                                    "FROM TonKho \n " +
                                                    "WHERE KhoID = @KhoID AND SoLuong <> 0 \n" +
                                                    "   AND VatTuHangHoaID is NOT NULL");
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("KhoID", selectedKhoID);
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                else
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID \n" +
                                                   "FROM NhatKyKho \n" +
                                                   "WHERE  @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi  \n" +
                                                   "	AND VatTuHangHoaID is NOT NULL \n" +
                                                   "UNION \n" +
                                                   "SELECT DISTINCT VatTuHangHoaID  \n" +
                                                   "FROM TonKho  \n" +
                                                   "WHERE SoLuong <> 0 \n" +
                                                   "	AND VatTuHangHoaID is NOT NULL ");

                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                DataTable dtDaCoGiaoDich = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtDaCoGiaoDich);
                return dtDaCoGiaoDich;
            }
            catch (Exception ex)
            {
                string message = string.Format("Lỗi [{0}] ở \n {1}", ex.Message, ex.StackTrace.Substring(0, ex.StackTrace.IndexOf("\n")));
                throw new CustomException(message);
                return null;
            }
        }
    }
}
